import router from "@/router";
// import { generateUrl, getUserInfo } from "@/api/common";

let qycode: any = null;
const agentId = 123;

router.beforeEach(async (to, from, next) => {
  next();
  return;
  // if (import.meta.env.VUE_APP_ENV === "development") {
  //   sessionStorage.setItem("Authorization",
  //   "Bearer 26563b04-72c3-41bd-b415-f8fa416edfc3");
  // }
  // 获取token,有token或不需要登录的页面直接进入
  if (sessionStorage.getItem("Authorization")) {
    next();
    return;
  } else {
    qycode = getUrlParam("code");
    console.log(qycode, "qycode");
    if (qycode) {
      // 用户未登录
      handleQyLogin(next);
    } else {
      getRedirctUrl();
    }
  }
});

// 获取重定向链接
function getRedirctUrl() {
  let path = window.location.href.split("#") != undefined ? window.location.href.split("#")[1] : "";
  let redirectUrl = window.location.origin + window.location.pathname + "#" + path;
  console.log(redirectUrl);
  const param = {
    agentId,
    redirectUrl, //登录成功后的回调页面地址
  };
  // 调用接口获取授权url
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww66fdbb77732633c7&redirect_uri=${encodeURI(
    "http://qyfocus.com:8000/report-statistic"
  )}&response_type=code&scope=snsapi_base&state=222333&agentid=1000002#wechat_redirect`;
  // generateUrl(param)
  //   .then((res) => {
  //     if (res.code === 200) {
  //       window.location.href = res.data;
  //     }
  //   })
  //   .catch((err) => {
  //     console.log(err);
  //   });
}

// 获取token
async function handleQyLogin() {
  try {
    const param = {
      code: qycode,
      agentId,
    };
    const res = await getUserInfo(param);
    if (res.code === 200) {
      // sessionStorage.setItem("userId", res.data.userId);
      sessionStorage.setItem("Authorization", "Bearer " + res.data.access_token);
      let code = window.location.search.substr(1),
        suffix = window.location.hash,
        prefix = window.location.href.split("?")[0],
        connector = suffix.includes("?") ? "&" : "?",
        r_url = `${prefix}${suffix}${connector}${code}`;
      window.location.replace(r_url);
    }
  } catch (error) {
    console.log(error);
  }
}

function getUrlParam(name: string) {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
export default router;
